﻿

using System;
using System.Linq;
using Demo.Domain;
using Demo.Repository;

namespace Demo.Repository
{
    public class ActionRepository : IActionRepository
    {
        DemoContext db = new DemoContext();

        public void CreateAction(string name, int moduleId, int sort = 0)
        {
            var action = new Demo.Domain.Action() { Name = name, ModuleID = moduleId, Sort = sort };
            db.Action.Add(action);
            db.SaveChanges();
        }

        public Domain.Action GetActionWithName(string name)
        {
            return db.Action.Where(a => a.Name == name).FirstOrDefault();
        }

        public Domain.Action GetActionWithId(int id)
        {
            return db.Action.Where(a => a.ActionID == id).FirstOrDefault();
        }

        public System.Collections.Generic.IList<Domain.Action> GetActionWithUserId(int userid)
        {
            var express = db.UserModule.Where(s=>s.UserID==userid).Select(s=>s.UserModuleID).ToList();
            var expressLinq = db.UserModuleAction.Where(s=>express.Contains(s.UserModuleID)).Select(s=>s.ActionID).ToList();
            return db.Action.Where(a => expressLinq.Contains(a.ActionID)).ToList();
        }

        public System.Collections.Generic.IList<Domain.Action> GetAction()
        {
            return db.Action.ToList();
        }

        public bool ChangeActionWithName(string oldName, string newName)
        {
            var action = db.Action.Where(a => a.Name == oldName).FirstOrDefault();
            action.Name = newName;
            db.SaveChanges();
            return true;
        }

        //public bool ChangeActionWithName(string Name, int newModuleId)
        //{
        //    var action = db.Action.Where(a => a.Name == Name).FirstOrDefault();
        //    action.ModuleID = newModuleId;
        //    db.SaveChanges();
        //    return true;
        //}
    }
}
